package com.gbei.center.controller;

import com.gbei.center.common.Constants;
import com.gbei.center.model.AuthorizationResponse;
import com.gbei.center.model.User;
import com.gbei.center.utils.EncryptUtils;
import com.gbei.center.utils.JsonUtils;
import com.gbei.center.utils.SingletonStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;

/**
 * 登录
 */
@Controller
public class LoginController {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${own.oauth2.client-id}")
    private String clientId;

    @Value("${own.oauth2.client-secret}")
    private String clientSecret;

    @Value("${own.oauth2.user-authorization-uri}")
    private String authorizationUri;

    @Value("${own.oauth2.access-token-uri}")
    private String accessTokenUri;

    @Value("${own.oauth2.resource.userInfoUri}")
    private String userInfoUri;

    /**
     * 登录验证（实际登录调用认证服务器）
     * @param request HttpServletRequest
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //当前系统登录成功之后的回调URL
        String redirectUrl = request.getParameter("redirectUrl");
        //当前系统请求认证服务器成功之后返回的Authorization Code
        String code = request.getParameter("code");

        //最后重定向的URL
        String resultUrl = "";
        HttpSession session = request.getSession();
        //当前请求路径
        String currentUrl = request.getRequestURL().toString();

        //code为空，则说明当前请求不是认证服务器的回调请求，则重定向URL到认证服务器登录
        if (StringUtils.isBlank(code)) {
            //如果存在回调URL，则将这个URL添加到session
            if (StringUtils.isNoneBlank(redirectUrl)) {
                session.setAttribute(Constants.SESSION_LOGIN_REDIRECT_URL, redirectUrl);
            }

            //生成随机的状态码，用于防止CSRF攻击
            String status = EncryptUtils.getRandomStr1(6);

            //单例类保存状态码
            SingletonStatus singletonStatus = SingletonStatus.getInstance();
            singletonStatus.setMsg(status);

            //拼装请求Authorization Code的地址
            resultUrl = MessageFormat.format(authorizationUri, clientId, status, currentUrl);
           return new ModelAndView("redirect:" + resultUrl);

        } else {

            //2. 通过Authorization Code获取Access Token
            String responseJson = restTemplate.getForObject(accessTokenUri, String.class, clientId, clientSecret, code, currentUrl);

            System.out.println("返回结果为 ： " + responseJson);

            Map<String, Object> responseMap = JsonUtils.fromJson(responseJson, Map.class);

            if ((int) responseMap.get("code") == 10000) {
                Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");

                String token = (String) dataMap.get("access_token");

                //2.1 将Access Token存到session
                session.setAttribute(Constants.SESSION_ACCESS_TOKEN, token);

                //2.2 查询用户基础信息
                String userJson = restTemplate.getForObject(userInfoUri, String.class, token);

                System.out.println("userJson = " + userJson);
                Map<String, Object> userMap = JsonUtils.fromJson(responseJson, Map.class);

                if ((int) userMap.get("code") == 10000) {
                    resultUrl += "/user/userIndex";
                    return new ModelAndView("redirect:" + resultUrl);
                }
                resultUrl = "/user/index";
                return new ModelAndView("redirect:" + resultUrl + "?result=用户基础信息为空");

            } else {
                resultUrl += "/user/index";
                int code1 = (int) responseMap.get("code") ;
                return new ModelAndView( "redirect:" +resultUrl + "?resultCode=" + code1);
            }
        }

    }
}
